package com.feige.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feige.annotation.PageInfo;
import com.feige.constant.Constants;
import com.feige.result.AjaxResult;
import com.feige.utils.http.ResponseUtil;
import com.feige.utils.http.ServletUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author feige<br />
 * @ClassName: PageMethodArgumentResolver <br/>
 * @Description: <br/>
 * @date: 2022/4/2 16:05<br/>
 */
@Component
public class PageMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(PageInfo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        PageInfo page = parameter.getParameterAnnotation(PageInfo.class);
        HttpServletRequest request = ServletUtils.getRequest();
        HttpServletResponse response = ServletUtils.getResponse();
        String pageNum = request.getParameter(Constants.PAGE_NUM_NAME);
        String pageSize = request.getParameter(Constants.PAGE_SIZE_NAME);
        if (page != null && StrUtil.isNotBlank(pageNum)){
            if (StrUtil.isBlank(pageSize)){
                return new Page<>(Long.parseLong(pageNum), page.pageSize());
            }else {
                return new Page<>(Long.parseLong(pageNum), Long.parseLong(pageSize));
            }
        }else {
            ResponseUtil.out(response, AjaxResult.error(500, "分页参数为空，请重试！"));
        }
        return null;
    }
}
